package utils

import (
	"log"
	"sync"
	"time"

	gocache "github.com/patrickmn/go-cache"
)

var ins *gocache.Cache
var once sync.Once

const cachefilename string = "go-cache.file"

func getgocache() *gocache.Cache {
	once.Do(func() {
		// Create a cache with a default expiration time of 5 minutes, and which
		// purges expired items every 10 minutes
		ins = gocache.New(5*time.Minute, 10*time.Minute)
	})
	return ins
}

// GetCache 提取缓存结果
func GetCache(key string) interface{} {
	c := getgocache()

	if len(key) == 0 {
		panic("缓存键值不允许为空")
	}

	value, ok := c.Get(key)
	if !ok {
		// 尝试还原
		err := c.LoadFile(cachefilename)
		if err != nil {
			log.Println("go-cache LoadFile(cachefilename) 报错:", err.Error())
			return nil
		}
		value, ok := c.Get(key)

		log.Println("go-cache 未发现", key, "的缓存，尝试从文件", cachefilename, "中加载数据")

		if !ok {
			log.Println("go-cache 未发现", key, "的缓存，尝试从文件", cachefilename, "中加载数据， 加载失败")
			return nil
		}
		log.Println("go-cache 未发现", key, "的缓存，尝试从文件", cachefilename, "中加载数据， 加载成功：", value)
		return value
	}
	return value
}

// SetCache 设置缓存
func SetCache(key string, val interface{}, expire time.Duration) {
	c := getgocache()

	if len(key) == 0 {
		panic("缓存键值不允许为空")
	}
	c.LoadFile(cachefilename)
	c.Set(key, val, expire)
	c.SaveFile(cachefilename)
}
